package com.lw.leetcode.arr;

/**
 * 面试题 17.10. 主要元素
 *
 * @Author liw
 * @Date 2021/5/20 17:54
 * @Version 1.0
 */
public class MajorityElement {

    public int majorityElement(int[] nums) {
        if (nums == null || nums.length == 0) {
            return  -1;
        }
        int i = find(nums);
        int count = 0;
        for (int num : nums) {
            if (num == i) {
                count++;
            }
        }
        if (count  > (nums.length >> 1)) {
            return i;
        }
        return -1;
    }

    private int find(int[] nums) {
        int value = 0;
        int count = 0;
        for (int num : nums) {
            if (count == 0) {
                value = num;
                count = 1;
            } else {
                if (num == value) {
                    count++;
                } else {
                    count--;
                }
            }

        }
        return value;
    }

}

